package cn.zf233.springsecurityjwt.config;

import cn.zf233.springsecurityjwt.entity.User;
import cn.zf233.springsecurityjwt.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by zf233 on 2021/7/12
 */
@Slf4j
@Service("jwtDetailsService")
public class JwtDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("准备加载用户:'{}'信息:", username);
        User userByUsername = userService.getUserById(Long.parseLong(username));
        if (userByUsername != null) {
            log.info("准备权限信息");
            String role = userByUsername.getRole();
            String[] roles = role.split("\\|");
            List<GrantedAuthority> authorityList = new ArrayList<>();
            for (String roleName : roles) {
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + roleName.toUpperCase(Locale.ROOT));
                authorityList.add(authority);
            }
            userByUsername.setAuthorities(authorityList);
            log.info("用户:'{}'加载通过", username);
            return userByUsername;
        }
        log.info("用户:'{}'加载失败", username);
        return null;
    }
}
